<template>
	<view  v-if="defaultShow">
		<view v-if="show">
			<view class="content-box">
				<view class="btn-box">
					<button class="button submit" @click="showErrToast('请先勾选隐私协议')" v-if="!agree">注册</button>
					<button class="button submit" id="agree-btn" open-type="getPhoneNumber|agreePrivacyAuthorization" @getphonenumber="getPhoneNumber" @agreeprivacyauthorization="handleAgree" v-else>注册</button>
					<button class="button cancellation" @click="backFn" >取消</button>
				</view>
			</view>
		
			<!-- <view class="attention">
				点击授权表示您已同意<text @click="toagreement"style="color: #007AFF;">《用户服务协议》</text>
			</view> -->
			<view class="button-box" @click="agree=!agree">
				<view>
					<checkbox-group ><checkbox :checked="agree" style="transform:scale(0.8) ;"/></checkbox-group>
					<view  class="text" style="font3-size: 26upx;color: #909399;bottom: 50upx;">
						我已阅读并同意
						<text @click.stop="openPrivacyContract" style="color: #007AFF;">《隐私协议》</text>
					</view>
				</view>
			</view>
		</view>
		<view v-else>
			<view class="loadding-box">
				<image class="loadding-img" src="/static/loadding.png" mode=""></image>
			</view>
		</view>
	</view>
	
</template>

<script>
	var WXBizDataCrypt = require('@/utils/RdWXBizDataCrypt.js');
	import config from "@/config.js"
	import log from "@/commom/logStorage.js"
	
	export default {
		data() {
			return {
				defaultShow: true,
				agree: false,
				appId: getApp().globalData.appId,
				sessionkey: uni.getStorageSync('sk'),
				wxOpenId: uni.getStorageSync('openId'),
				pubopenid: getApp().globalData.pubopenid,
				gradeid: getApp().globalData.gradeId,
				schoolId: getApp().globalData.schoolId,
				info: '',
				newUser: uni.getStorageSync("newUser"),
				show: false,
				className: '请选择组织',
				phoneNumber: "",
				
				tenantId : config.TENANT_ID
			}
		},
		methods: {
			init(){
					this.getClassList().then(res=>{
						this.login()
					}).catch(err=>{
						uni.showToast({
						  icon: "none",
						  title: "获取班级列表失败：" + err.message
						});
					})
				wx.getPrivacySetting({
					success:res=>{
						this.protocol = res.privacyContractName
					}
				})
			},
			openPrivacyContract(){
				wx.openPrivacyContract({
					success: (res) => {
					},
				})
			},
			handleDisagree() {
				this.showPrivacyMask = false
			},
			handleAgree() {
				this.showPrivacyMask = false
			},
			showErrToast(title){
				uni.showToast({
					icon: 'none',
					title: title
				})
			},
			login() {
				let that = this
				uni.login({
					success(res2) {
						that.getOpenId(res2.code)
					}
				})
			},
			getOpenId(code) {
				this.$http('/pay/api/wechart/getSessionNew', {
					code: code,
					appId: this.appId
				}, res3 => {
					this.wxOpenId = res3.data.openid
					this.sessionkey = res3.data.sk ? res3.data.sk : res3.data.session_key
					uni.setStorageSync('openId', res3.data.openid)
					uni.setStorageSync('sk', res3.data.sk)
					log.info(`pages:bind.vue; method: login; oId: ${this.wxOpenId} ;机构id: ${this.schoolId}; 班级id: ${this.gradeid}`)
					log.info(`pages: bind.vue; method: getOpenId, api: restfull/getSessionNew; code: ${code}; oId: ${this.wxOpenId} `)
					this.$http('/minprogram/api/member/verify', {
						"wxOpenId": uni.getStorageSync('openId'),
						"pubOpenId": this.pubopenid
					}, res4 => {
						uni.hideToast()
						uni.reLaunch({ url: '/pages/tabbar/my' })
					}, 'POST', () => {
						this.newUser = true
						uni.setStorageSync("newUser", this.newUser)
						this.show = true
					}, false)
				}, 'GET')
			},
			getClassList() {
				return new Promise((resolve, reject) => {
				  this.$http('/member/api/organization/list', {
				    "condition": { "parentId": this.schoolId },
				  }, res => {
				    if (res.data.items && res.data.items.length > 0) {
				      this.gradeid = res.data.items[0].id;
				      resolve(res);
				    } else {
				      uni.showToast({
				        icon: "none",
				        title: "未配置机构区域"
				      });
				      reject(new Error("未配置机构区域"));
				    }
				  });
				});
			},
			getLogin() {
				this.$http('/minprogram/api/member/verify', {
					"wxOpenId": uni.getStorageSync('openId'),
					"pubOpenId": this.pubopenid
				}, res4 => {
					let faceCount_log = this.info.faceCount;
					log.info(`pages: bind.vue; method: getLogin ; restfull/verify; oId: ${this.wxOpenId} this.info.faceCount: ${faceCount_log}`)
					uni.setStorageSync('token', res4.data.token)
					if (this.info.faceCount > 0) {
						uni.reLaunch({ url: '/pages/tabbar/my' })
					}else {
						this.show = true
					}
				}, 'POST', () => {
					uni.hideToast()
					this.newUser = true
					uni.setStorageSync("newUser", this.newUser)
					this.show = true
				}, false)
			},
			async getPhoneNumber(e) {
				let that = this
				if (e.detail.errMsg == "getPhoneNumber:fail user deny") { //用户决绝授权  
					
					uni.showToast({
						title: '请同意获取手机号码'
					});
					
					console.log("用户拒绝获取手机号码");
				
				} else {
					
					if(!this.gradeid){
						uni.showToast({
							icon: "none",
							title: "未配置机构区域"
						})
						return;
					}
					
					uni.showLoading({
						mask: true,
						title: "正在注册..."
					})
					var pc = new WXBizDataCrypt(this.appId, this.sessionkey);
					var data = pc.decryptData(e.detail.encryptedData, e.detail.iv)
					
					this.phoneNumber = data.phoneNumber;
					
					if (this.newUser) {

						await new Promise((aaa, bbb) => {
							this.$http('/minprogram/api/member/bind', {
								"wxOpenId": this.wxOpenId,
								"phone": data.phoneNumber,
								"wxName": data.phoneNumber,
								"pubOpenId": this.pubopenid,
								"businessModel":6
							}, result => {
								uni.setStorageSync('token', result.data.token)
								
								log.info(`pages: bind.vue; method: getPhoneNumber , api:restfull/bind , oId: ${this.wxOpenId} , 新用户： ${this.newUser} `)
								
								this.newUser = false
								uni.setStorageSync("newUser", this.newUser)
								
								this.$http('/minprogram/api/member/getStudentInfo', {
									"ownerName": "洗宠用户" + this.phoneNumber.substr(-4),
									"schoolId": this.schoolId,
									"gradeId": this.gradeid
								}, res => {
									if (res.data.phone) {
										if (res.data.phone == this.phoneNumber) {
											log.info(`pages: bind.vue; method: getPhoneNumber , api: restfull/getStudentInfo , oId: ${this.wxOpenId} , 已经跟机构绑定 `)
											uni.hideLoading()
											uni.reLaunch({ url: '/pages/tabbar/my' })
										}
									} else {
										this.addFace()
									}
								}, 'GET')		
								// uni.showToastCallBack({
								// 	icon: "none",
								// 	title: "注册成功",
								// 	mask: true
								// }, () => {
								// 	uni.reLaunch({ url: '/pages/tabbar/my' })
								// })
								aaa()
							})
						})
					}else {
						log.info(`pages: bind.vue; method: getPhoneNumber , api: , oId: ${this.wxOpenId} , 不是新用户 `)
					}
				}
			},
			addFace() {
				this.$http('/minprogram/api/member/saveOwnerStudent', {
					"ownerName": "洗宠用户" + this.phoneNumber.substr(-4),
					"organizationId": this.schoolId,
					"gradeId": this.gradeid,
				}, res => {
					if (res.data.value) {
						log.info(`pages: bind.vue; method: addFace , api: restfull/saveOwnerStudent , oId: ${this.wxOpenId} , 机构绑定成功 `)
						uni.showToastCallBack({
							icon: "none",
							title: "注册成功",
							mask: true
						}, () => {
							uni.reLaunch({ url: '/pages/bind/bind' })
						})
					}
				},"POST",(err)=>{
					log.info(`pages: bind.vue; method: addFace , api: restfull/saveOwnerStudent , oId: ${this.wxOpenId} , 机构绑定失败； err: ${err} `)
					uni.hideLoading()
					uni.showToast({
						icon: err
					})
				})
			},
			// 提取所有参数
			queryParse(url) {
				var paramObj = {};
				if (url.indexOf('?') > -1) {
					var _url = url.split('?')[1].split('#')[0];
					var strArr = _url.split('&');
					strArr.forEach(ele => {
						var key = ele.split('=')[0];
						var val = ele.split('=')[1];
						paramObj[key] = val;
					});
				}
				return paramObj;
			},
			backFn(){
				this.$emit("close")
			},
			logReport() {
				let log = uni.getStorageSync("w_log");
				uni.setClipboardData({
					data: log ,
					success: () => {
						uni.showToast({
							icon: "none",
							title: "复制成功"
						})
					}
				})
			}
		},
	}
</script>

<style scoped lang="less">
	.default-show{
		width: 100vw;
		height: 100vh;
		image{
			width: 100%;
			height: 100%;
		}
	}
	.content-box{
		position: relative;
		background: rgba(255, 255, 255, .3);
		border-radius: 16upx;
		padding: 30upx 20upx 10upx;
		.ava{
			position: absolute;
			left: 50%;
			top: -60upx;
			margin-left: -60upx;
			width: 120upx;
			height: 120upx;
			border-radius: 50%;
			padding: 10upx;
			background: #fff;
			.avatar{
				width: 100%;
				height: 100%;
			}
		}
		.cardNum{
			background: #fff;
			border-radius: 16upx;
			padding: 0 30upx;
			.school-name{
				display: flex;
				flex-direction: row;
				align-items: center;
				margin: 16upx 0 36upx 10upx;
				
				.school-name-text{
					color: #F72F18;
				}
				
				.school-name-icon{
					width: 36rpx;
					height: 36rpx;
					margin-right: 14rpx;
				}
				
			}
			
			.label-box{
				display: flex;
				align-items: center;
				height: 88upx;
				margin-bottom: 22upx;
				.icon-logo{
					width: 50upx;
					height: 50upx;
					margin-right: 16upx;
				}
				.right-ipt{
					width: 520upx;
					background: #f2f2f2;
					height: 70upx;
					display: flex;
					align-items: center;
					padding: 0 10upx;
					font-size: 26upx;
					color: #999;
					border-radius: 6upx;
					justify-content: space-between;
					image{
						transform: rotate(90deg);
						width: 20upx;
						height: 20upx;
						margin-right: 12upx;
					}
				}
			}
		}
		.btn-box{
			background: #fff;
			border-radius: 16upx;
			padding: 0 30upx;
			.button{
				width: 100%;
				height: 88upx;
				text-align: center;
				line-height: 88upx;
				border-radius: 44upx;
				font-size: 28upx;
			}
			.button~.button{
				margin-top: 20upx;
			}
			.submit{
				background: linear-gradient(to right, #F72F18, #FA6018);
				color: #fff;
			}
			.cancellation{
				background: #e4e4e4;
				color: #6a6a6a;
			}
		}
	}
	.attention{
		font-size: 24upx;
		color: #909399;
		position: fixed;
		bottom: 20upx;
		width: 100%;
		text-align: center;
	}
	.button-box {
		width: 700upx;
		display: flex;
		justify-content: center;
		border-radius: 20upx;
		box-sizing: border-box;
		
		>view {
			padding: 0 30rpx;
			font-size: 26upx;
			display: flex;
			align-items: center;
		}
	}
	
	.zzc{
		width: 100vw;
		height: 100vh;
		position: fixed;
		top: 0;
		background-color: rgba(0,0,0,0.4);
		z-index: 100;
		>view{
			width: 100%;
			height: 700upx;
			background-color: #FFFFFF;
			position: absolute;
			bottom: 0;
			box-sizing: border-box;
			>view.btn{
				width: 100%;
				height: 80upx;
				display: flex;
				justify-content: space-between;
				// border-bottom: 1upx solid #dddddd;
				>view{
					height: 100%;
					width: 160upx;
					font-size: 24upx;
					line-height: 80upx;
					text-align: center;
					color: #999999;
				}
			}
			>view.search{
				width: 100%;
				>input{
					background-color: #eeeeee;
					width: 90%;
					margin: 0 auto;
					height: 70upx;
					border-radius: 10upx;
					text-align: center;
				}
			}
			>view.box{
				width: 100%;
				height: 100%;
				box-sizing: border-box;
				padding: 20upx 0;
				.picker-area{
				        width: 100%;
				        height: 100%;
						text-align: center;
				    }
				.item{
					line-height: 34px;
				}
			}
		}
	}
	.loadding-box{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		.loadding-img{
			width: 88rpx;
			height: 88rpx;
			margin-top: 88rpx;
			margin-left: 88rpx;
			animation:loadingRotate 1s infinite linear;
			-moz-animation:loadingRotate 1s infinite linear;
			-webkit-animation:loadingRotate 1s infinite linear;
			-o-animation:loadingRotate 1s infinite linear;
			@keyframes loadingRotate {
			  from { transform: translate(-50%, -50%) rotate(0); }
			  to { transform: translate(-50%, -50%) rotate(360deg); }
			};
			@-webkit-keyframes loadingRotate {              
				from { transform: translate(-50%, -50%) rotate(0); }
				to { transform: translate(-50%, -50%) rotate(360deg); }
			};
			@-moz-keyframes loadingRotate {
			       from { transform: translate(-50%, -50%) rotate(0); }
			       to { transform: translate(-50%, -50%) rotate(360deg); }
			     };
			     @-o-keyframes loadingRotate {   
			       from { transform: translate(-50%, -50%) rotate(0); }
			       to { transform: translate(-50%, -50%) rotate(360deg); }
			   };
			}
	}
	
</style>